"---------------------------------------------------------------------------
" vimrc functions:
"

function! vimrc#on_filetype() abort
  if execute('filetype') =~# 'OFF'
    " Lazy loading
    silent! filetype plugin indent on
    syntax enable
    filetype detect
  endif
endfunction

function! vimrc#windowjump(i) abort
  let cur_winid = win_getid()
  let cur_winnr = winnr()
  let pre_winnr = win_id2win(g:pre_winid)
  let max_winnr = winnr('$')
  if max_winnr >= a:i  " 合法性检查
    if cur_winnr == a:i  " 与i3 workspace跳转行为相同
      if pre_winnr != 0
        exe pre_winnr . 'wincmd w'
      endif
    else
      exe a:i . 'wincmd w'
    endif
  endif
endfunction

" let last_winnr = winnr('#')

function! vimrc#cdNode(context) abort
    let [curdir] = a:context.targets
    :py3 << EOF
import vim
from pathlib import Path
str = vim.eval('curdir')
path = Path(str)
if not path.is_dir():
  path = Path(str).parent
print(path)
vim.command(f"let dir='{path}'")
EOF
    exe 'cd ' . dir
endfunction

function! vimrc#open_default_shell() abort
  exe 'topleft split'
  let lines = &lines * 28 / 100
  if lines < winheight(0)
    exe 'resize ' . lines
  endif
  if g:Windows
    let shell = empty($SHELL) ? 'powershell.exe' : $SHELL
  else
    let shell = empty($SHELL) ? 'zsh' : $SHELL
  endif
  if has('nvim')
    exe 'terminal '.shell
    " setlocal nonumber norelativenumber
    " setlocal statusline=%{b:term_title}
  else
    call term_start(shell, {'curwin' : 1, 'term_finish' : 'close'})
  endif
  setlocal nobuflisted
  startinsert
endfunction
